//data
let appId;
let appInfo;
let baseEntity;
let panoinfos = {};//首页全景
let facility_list = [];//设施
let entityGroupList = {};//子实体分组列表
let subEntityGroup = {};//子实体分组
let indexAppearanceMarkers = {};//首页外观makers
let facilityMap = {};//设施集合，通过子实体获取
let facilityEntityMap = {};//设施，实体map
let appearanceMap = {};//子实体的外观（【外观ID，实体ID】）
let isIndex = true;//是否为首页
let viewfacilitys = {};//已浏览过的设施
let appCount; //浏览数和点赞数
//let jszhan;//是否点赞
let isShowWelcome = false;
let isSmallMap = true; //默认为小地图模式
let facToEnt={};//设施ID —> 实体ID 映射表
var model;//三维模型
//设施ID —> 实体ID 映射表
$.ajax({
    url: 'js/facility_entity_map.txt',
    dataType: 'text',
    success: function (data) {
        facToEnt = JSON.parse(data);
        // console.log(JSON.parse(data));
    }
});

//同步执行
$.ajaxSettings.async = false;

// 正则表达式，根据URL参数返回特定的值
function getQueryString(name) {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

appId = getQueryString("appId");
if (!appId) {
    appId = 5663;
}

let setWechartTitle = function (title) {
    let $body = jQuery('body');
    document.title = title;
    let $iframe = jQuery("<iframe style='display:none;'></iframe>");
    $iframe.on('load', function () {
        setTimeout(function () {
            $iframe.off('load').remove();
        }, 50);
    }).appendTo($body);
};

// 根据URL判断是先线上环境还是测试环境
let env = function () {
    let host = document.location.host;
    let pathname = document.location.pathname;
    let env = 'online';
    // 判断是测试环境的条件
    if ((/debug/.test(pathname) && /webapp.vizen.cn/.test(host) && getQueryString("env") != "1") || getQueryString("env") == "2") {
        env = 'test'
    } else if (/webapp.vizen.cn/.test(host)) {
        env = 'online'
    } else if (/localhost|127.0.0.1|192.168.1|test.com/g.test(host)) {
        env = 'local'
    }
    return env
};

let baseUrl = {
    online: document.location.protocol + '//api.show.vizen.cn',
    test: document.location.protocol + '//api.show.test.vizen.cn',
    local: document.location.protocol + '//api.show.vizen.cn'
};
let apiBaseUrl = baseUrl[env()];


//获取应用点击，整个应用的第一个请求-----注意这里使用的不是异步请求，获得的数据包括：APPid、点赞数和观看人数
$.ajax({
    type: "GET",
    async: false,
    url: apiBaseUrl + "/api/app/actionsCount?appId=" + appId,
    success: function (dt) {
        appCount = dt.data;
    }
});

//是否点击
$.ajax({
    type: "GET",
    async: false,
    url: apiBaseUrl + "/api/app/thumbUpStatus?appId=" + appId + "&deviceCode=1234",
    success: function (dt) {
        jszhan = dt.data;
    }
});

//用户浏览计数  无返回数据,每执行一次,数据库该markerId对应的浏览次数(visitCount )＋1，
$.ajax({
    type: "GET",
    async: false,
    data: parseInt(appCount.visitCount) + 1,
    url: apiBaseUrl + "/api/app/browse?appId=" + appId
});

//点赞+1 无返回数据,每执行一次,数据库该appId对应的点赞次数(thumbUpCount )+1
function like() {
    //if (!jszhan) {
    $.ajax({
        type: "POST",
        data: parseInt(appCount.thumbUpCount) + 1,
        url: apiBaseUrl + "/api/app/thumbUp?appId=" + appId
    });
    $(".like-wrap p").html(appCount.thumbUpCount + 1);
    //}
}

//设置点击量
$(".like-wrap p").html(appCount.thumbUpCount);


//获取应用信息
$.ajax({
    type: "GET",
    async: false,
    url: apiBaseUrl + "/api/app/" + appId,
    success: function (dt) {
        if (dt.code != "0") {
            alert(dt.msg);
            return;
        }
        appInfo = dt;
        // 获取应用的标题名称
        setWechartTitle(appInfo.data.name)
        //实例化三维模型
        model = new com.vbr3d.Model(document.getElementById("threeDContainer"));
    }
});

//获取实体信息
$.ajax({
    type: "GET",
    async: false,
    url: apiBaseUrl + "/api/app/entity/list/" + appId,
    success: function (dt) {
        if (dt.code != "0") {
            alert(dt.msg);
            return;
        }
        let entityId = dt.data[0].entityList[0].id;
        $.ajax({
            type: "GET",
            async: false,
            // 利用上一层接口的id当成参数传递到下一层
            url: apiBaseUrl + "/api/app/entity/" + entityId,
            success: function (dt) {
                baseEntity = dt;
            }
        });
    }
});

//页面标题
$("title").html(appInfo.data.name);

//首页简介
$(".swiper-ggInfo .swiper-slide").html(baseEntity.data.intro.replace(/[\n]/g, "<br />"));

//背景音乐
let mp3 = '<audio src="' + appInfo.data.audio + '" id="audio" preload="auto" autoplay="autoplay"    loop="loop" style="display: none;"></audio>';
$(".bgMuisc").append(mp3);

let isMusic = true;

var audio = $("#audio")[0];

//点击子实体外观maker 更改实体信息
function changeEntityInfo(EntityData) {

    //上滑内容
    $(".onTheBotton .inner-title").html(EntityData.data.name);
    $(".onTheBotton .palace-info").html(EntityData.data.intro.replace(/[\n]/g, "<br />"));

    $(".container-wrap .inner-title").html(EntityData.data.name);
    $(".container-wrap .swiper-slide p").html(EntityData.data.intro.replace(/[\n]/g, "<br />"));
    initInnerRoll();

    //语言介绍
    if (EntityData.data.audioIntro.length > 0) {//有
        $(".voice").show();
        $("#audioIntro").attr("src", EntityData.data.audioIntro)
    } else {
        $(".voice").hide();
    }
}


//首页外观全景信息
// 就是一张全景图片，和一个panos的数组
let appearancesInfo;
$.ajax({
    type: "GET",
    async: false,
    url: apiBaseUrl + "/api/app/entity/appearance?entityId=" + baseEntity.data.id + "&preview=0",
    success: function (dt) {
        appearancesInfo = dt.data;
    }
});

// 通过外观信息 得到 materialId 和 facilityId 生成 appearances_data数组
let appearances_data = [];
for (let i = 0; i < appearancesInfo[0].panos.length; i++) {
    appearances_data[i] = apiBaseUrl + "/api/app/facility/marker?materialId=" + appearancesInfo[0].panos[i].id + "&facilityId=" + appearancesInfo[0].id + "&preview=0"
}

let appearances = [];
for (let d in appearances_data) {
    $.ajax({
        type: "GET",
        async: false,
        url: appearances_data[d],
        success: function (dt) {
            appearances.push(dt);
            //添加到首页的marker列表
            for (let i = 0; i < dt.data.marker.length; i++) {
                indexAppearanceMarkers[dt.data.marker[i].id] = dt.data.marker[i];
            }
        }
    });
}

//把外观加入到pano列表
for (let i = 0; i < appearances.length; i++) {
    //console.log("===");
    //console.log(appearances[i].data);
    panoinfos[i] = appearances[i].data;
}

//获取子实体(分类)
let sub_entitys_url = apiBaseUrl + "/api/app/entity/subEntities?entityId=" + baseEntity.data.id + "&preview=1";
let subEntitys = [];
$.ajax({
    type: "GET",
    async: false,
    url: sub_entitys_url,
    success: function (dt) {

        entityGroupList = dt.data.entityGroupList;

        for (let i = 0; i < dt.data.entityGroupList.length; i++) {
            //实体分组
            subEntityGroup[dt.data.entityGroupList[i].id] = dt.data.entityGroupList[i].subEntityList;
        }
    }
});


//点击marker切换或者显示对应设施列表(注意要判断目标全景是外观还是设施，如果是外观则获取全景信息展示)
function viewFacilityList(curEntityID) {
    //初始为默认状态
    $(".album-slide").removeClass("active").hide();

    //取得分组ID
    let groupId = $('.album-slide[id=' + curEntityID + ']').attr("groupid");

    console.log("groupId   "+groupId);

    $('.album-slide').hide();

    $('.album-slide[groupid=' + groupId + ']').show();

    //记录是否已播放
    viewfacilitys[curEntityID] = true;

    //遍历显示所有的
    $(".album-slide").each(function () {
        //判断是否显示对勾
        var f = $(this).attr("id");
        if (viewfacilitys[f]) {
            $('.album-slide[id=' + f + '] .icon-read').show();
        }
    });

    //当前添加边框 active

    $(".album-slide").removeClass("active");
    $('.album-slide[id=' + curEntityID + ']').addClass("active");


    //移除当前对勾
    $('.album-slide[id=' + curEntityID + '] .icon-read').hide();


    //获取active前显示元素的数量
    let showPveNum = $(".album-wrapper .album-slide.active").prevAll(".album-slide:visible").length;
    console.log("showPveNum" + showPveNum);
    albumSwiper.slideTo(showPveNum, 0);


    //改变地图当前浏览
    $(".architecture-marker[group='宫殿'] .architecture-icon").removeClass("curView");
    $(".architecture-marker[group='宫殿'] .architecture-icon").attr("src","./images/jianzhu.png");
    $(`.architecture-marker[id='${curEntityID}'] .architecture-icon`).addClass("active curView");
    $(`.architecture-marker[id='${curEntityID}'] .architecture-icon`).attr({"src":"./images/icon-guankan.png"});

}


//获取子实体的外观ID（第一个设施ID）
function getSubEntityAppearance(entityId) {
    var t_facilityId;
    $.ajax({
        type: "GET",
        async: false,
        url: apiBaseUrl + "/api/app/entity/appearance?entityId=" + entityId,
        success: function (pdt) {
            for (i = 0; i < pdt.data.length; i++) {
                t_facilityId = pdt.data[i].id;
                break;
            }
        }
    });
    return t_facilityId;
}

//根据子实体ID获得全景信息（实体》外观》全景）
function getPanoInfoBySubEntityId(entityId) {
    var t_facilityId;
    var t_materialId;
    var t_panoInfo;
    //获取子实体外观
    $.ajax({
        type: "GET",
        async: false,
        url: apiBaseUrl + "/api/app/entity/appearance?entityId=" + entityId,
        success: function (pdt) {
            for (i = 0; i < pdt.data.length; i++) {
                t_facilityId = pdt.data[i].id;
                for (j = 0; j < pdt.data[i].panos.length; j++) {
                    t_materialId = pdt.data[i].panos[j].id;
                    break;//取第一个外观
                }
            }
        }
    });
    //获取全景信息
    t_panoInfo = getPanoInfo(t_materialId, t_facilityId);
    return t_panoInfo.data;
}


//获取实体下的设施列表
function getFacilityList(entity_id) {
    var dat;
    var url = apiBaseUrl + "/api/app/facility/list?entityId=" + entity_id + "&facilityId=0&preview=0";
    $.ajax({
        type: "GET",
        async: false,
        url: url,
        success: function (dt) {
            dat = dt;
        }
    });
    return dat;
}


//获取设施分组
let facilityGroup;
$.ajax({
    type: "GET",
    async: false,
    url: apiBaseUrl + "/api/app/facility/list?facilityId=0&entityId=" + baseEntity.data.id + "&preview=0",
    success: function (dt) {
        facilityGroup = dt.data;
    }
});

//相册内容
// 获取子实体下所有设施设置子实体（功能调整，不显示子实体，而显示设施 外观属于一种特殊的设施）
let entityArr = [];
let linesPoi = "";

for (let i = 0; i < 9; i++) {
    for (let j = 0; j < entityGroupList[i].subEntityList.length; j++) {
        entityArr.push(entityGroupList[i].subEntityList[j].id);
        linesPoi += `
        <div class="album-slide swiper-slide" name="${entityGroupList[i].subEntityList[j].name}" groupID="${entityGroupList[i].id}" id="${entityGroupList[i].subEntityList[j].id}" poiId="${entityGroupList[i].subEntityList[j].poiId}">
            <div class="album-item">
                <img class="album-img" src="${entityGroupList[i].subEntityList[j].thumbnail}">
                <div class="album-mask">
                    <p>${entityGroupList[i].subEntityList[j].name}</p>
                </div>
                <img class="icon-read" src="./images/icon-read.png">
            </div>
        </div>`
    }
}

$(".album-wrapper").html("").append(linesPoi);

// 相册点击事件
$(document).on("click", ".album-slide", function () {

    //获取并展示设施信息
    let entityId = $(this).attr("id");
    let pInfo = getPanoInfoBySubEntityId(entityId);
    //console.log(pInfo);
    setPanoInfo(pInfo);

    //取得分组ID
    let groupId = $(this).attr("groupid");
    $('.album-slide').hide();
    $('.album-slide[groupid=' + groupId + ']').show();

    //记录是否已播放
    viewfacilitys[entityId] = true;

    //遍历显示所有的
    $(".album-slide").each(function () {
        //判断是否显示对勾
        var f = $(this).attr("id");
        if (viewfacilitys[f]) {
            $('.album-slide[id=' + f + '] .icon-read').show();
        }
    });
    //移除当前对勾
    $('.album-slide[id=' + entityId + '] .icon-read').hide();

    viewSubPageElement("pano");
    changeEntityInfo(getEntityInfo(entityId));



    //改变地图当前浏览
    $(".architecture-marker[group='宫殿'] .architecture-icon").removeClass("curView");
    $(".architecture-marker[group='宫殿'] .architecture-icon").attr("src","./images/jianzhu.png");
    $(`.architecture-marker[id='${entityId}'] .architecture-icon`).addClass("active curView");
    $(`.architecture-marker[id='${entityId}'] .architecture-icon`).attr({"src":"./images/icon-guankan.png"});


});

function showAlbum() {

    $(".photo-wrap i").addClass("active");
    $(".album-wrap").css("bottom", ".15rem");
    $(".inner-upglide").css("bottom", "0rem");
}

var hideAlbumTime;//设置隐藏相册的时间
function hideAlbum5s()
{
    hideAlbumTime= setTimeout(function () {

        $(".photo-wrap i").removeClass("active");
        $(".album-wrap").css("bottom", "-1.25rem");
        $(".inner-upglide").css("bottom", "-1.3rem");

    },15000)
}
$(document).on("click touchstart touchend", ".album-slide", function () {
    clearTimeout(hideAlbumTime);
    hideAlbum5s();
});


//隐藏/显示子页面元素（当点击全景页面的时候）
function viewSubPageElement(viewStatus) {
    if (viewStatus == "pano") {
        //子页面
        $(".header").fadeIn(1000);//头部
        $(".back-home").css("visibility", "visible");//返回
        $(".feature,.photo-wrap").fadeIn(1000);//右侧点赞、分享
        $(".inner-wrap").fadeIn(1000);//子页面内容
        $(".header-map").hide();//子页面内容

        //首页
        $(".home-logo").hide();//隐藏logo
        $(".home-wrap").hide(); //首页信息


        //$("#container").removeClass("containerBlur");

    } else if (viewStatus == "info") {//显示图片

        //子页面
        $(".header").hide();//头部
        $(".header-info").hide();//头部信息
        $(".feature").hide();//右侧点赞、分享
        $(".inner-wrap").hide();//子页面内容
        $(".palace-info").hide();
    }
}

//点击返回按钮
$(".back-home").on("click", function () {
    returnIndex();
    isIndex = true;
    //exploreSwiper.slideTo(0, 0, false);
});

//返回主页面
function returnIndex() {
    //清除延时
    delayShow = 0;

    //首页元素
    $(".home-logo").show();
    $(".back-home").css("visibility", "hidden");//返回
    $(".home-wrap").show(); //首页信息


    //子页面
    $(".inner-wrap").hide();//子页面内容
    $(".photo-wrap").hide();//右侧点赞、分享


    //语音介绍关闭
    changeSceneAudio();


    //显示默认全景
    setPanoInfo(panoinfos[0]);
}

//获取实体下的设施列表
function getFacilityList(entity_id) {
    let dat;
    let url = apiBaseUrl + "/api/app/facility/list?entityId=" + entity_id + "&facilityId=0&preview=0";
    $.ajax({
        type: "GET",
        async: false,
        url: url,
        success: function (dt) {
            dat = dt;
        }
    });
    return dat;
}

//根据设施ID获得全景信息,根据全景信息获得panno详情
function getPanoInfoByFacility(facilityId) {
    let data = null;
    $.ajax({
        type: "GET",
        async: false,
        url: apiBaseUrl + "/api/app/facility/" + facilityId,
        success: function (dt) {
            //取设施的第一张全景
            let materialId = dt.data.pano[0].id;
            //alert(materialId);
            // console.log(apiBaseUrl + "/api/app/facility/marker?materialId=" + materialId + "&facilityId=" + facilityId + "&preview=0");
            data = getPanoInfo(materialId, facilityId);
        }
    });
    return data;
}

//获取设施信息
function getFacilityInfo(facilityId) {
    let dat = null;
    $.ajax({
        type: "GET",
        async: false,
        url: apiBaseUrl + "/api/app/facility/" + facilityId,
        success: function (dt) {
            dat = dt;
        }
    });
    return dat;
}

//显示设施信息
function viewFacility(facility) {


}

//获取实体详情（获取并展示子实体）
function getEntityInfo(entityId) {
    let entityData;
    $.ajax({
        type: "GET",
        async: false,
        url: apiBaseUrl + "/api/app/entity/" + entityId,
        success: function (dt) {
            entityData = dt;
        }
    });
    return entityData;
}

function getPanoInfo(materialId, facilityId) {
    let rdata = null;
    $.ajax({
        type: "GET",
        async: false,
        url: apiBaseUrl + "/api/app/facility/marker?materialId=" + materialId + "&facilityId=" + facilityId + "&preview=0",
        success: function (dt) {
            rdata = dt;
        }
    });
    return rdata;
}


// 首页动画------------------------------------------------------------------------------------
let marker = [];
let panoView = null;
let pano = new com.vizengine.App(document.getElementById("container"), function () {

    // 是否逆时针转动
    var antiClockwise = false;

    var View = com.appengine.view.View;
    var PanoEffectAnimation = com.vizengine.animation.PanoEffectAnimation;
    panoView = new com.vizengine.view.PanoView();
    var page = window.rootView;

    panoView.setPanoEffect("smallplanet");
    panoView.touchable = false;

    //A2D0442EA5D34DA5BE2D90AAFFC40E4C 
    panoView.setPanoId("73725E4621244445ABFF8B9116126013", function () {
        //全景欢迎动画效果数据准备完毕，关闭loding...;
        panoView.setHeading(-380.2950972341691);
        panoView.setPitch(90)
        $("#loadingDiv").fadeOut();
        init();//开始播放欢迎动画效果
    });

    // panoView.setHeading();

    var showFov = 3;

    function init() {
        var heading0 = panoView.getRawHeading();
        var paras = {
            fps: 50,
            duration: 2000,
            fromHeading : antiClockwise ? heading0 + Math.PI*0.15 : heading0 - Math.PI*0.15,
            toHeading   : antiClockwise ? heading0 - Math.PI*2.00 : heading0 + Math.PI*2.0,
            fromScale: 20,
            toScale: showFov
        };
        var anima0 = new PanoEffectAnimation(paras);
        anima0.callback = function () {
            //动画效果放大完毕，开始匀速旋转
            runSpin();


        };
        panoView.playAnimation(anima0);

    }

    var timeoutFunc;

    //开始旋转的方法
    function runSpin() {
        //page.addView(btn);
        var heading0 = panoView.getRawHeading();
        var paras = {
            duration: 30000,
            repeatCount: 0,
            fromHeading: heading0,
            toHeading   : antiClockwise ? heading0 - 2 * Math.PI : heading0 + 2 * Math.PI
        };
        var animation = new PanoEffectAnimation(paras);
        panoView.playAnimation(animation);

        $(".gugong-text").addClass("active");

        //设置旋转8秒以后，进入首页全景
        timeoutFunc = setTimeout(function () {
            runEnter();
            // page.removeView(btn);

            //隐藏
            $(".gugong-text").hide();


        }, 8000);
    }

    //进入首页全景
    //切换动画，自动旋转角度，并由小行星效果转为正常全景。
    function runEnter() {
        if (timeoutFunc != null) {
            clearTimeout(timeoutFunc);
        }

        //2，动画切换的地方，setPanoId 方法增加进入动画
        // var anim = new com.vizengine.animation.PanoScaleSwitchAnimation;
        // panoView.setPanoId("A2D0442EA5D34DA5BE2D90AAFFC40E4C", null, anim);

        panoView.playAnimation(null);

        var heading = panoView.getRawHeading();
        heading = heading - Math.floor(heading / (Math.PI * 2)) * Math.PI * 2;

        panoView.setEffectMode(panoView.eEffectMode.PLANET2NORMAL);
        var paras = {
            duration    : 3000,
            fromHeading : heading,
            toHeading   : (antiClockwise ? 0 : Math.PI * 2)+0.12155,   //6.404740390094932
            fromPitch   : panoView.getRawPitch(),
            toPitch     : Math.PI/2 + 0.25,
            fromScale   : showFov,
            toScale     : 0.95,
            enableLerp  : true
        }

        var anim = new PanoEffectAnimation(paras);
        anim.callback = function () {

            //首页全景加载完毕可以开始加入marker点

            //移除所有marker
            removeAllMarker();
            let panoinfo = {}
            Object.assign(panoinfo, panoinfos[0]);

            //panoView.setHeading(panoinfo.heading || 0);
            //panoView.setPitch(panoinfo.pitch || 0);

            panoView.setAutoplayEnable(true);//自动旋转全景

            setTimeout(function () {

                $(".header,.home-wrap").fadeIn(1000);
                $(".feature").css("visibility", "visible");
                $(".feature").fadeIn(1000);

                //增加自动播放方向参数，为空时，默认为顺时针旋转。
               // PanoView.setAutoplayEnable(isAutoPlay:bool, antiClockwise:bool);


                panoView.setOnClick(function () {
                    panoOnClick()
                });


                //audio.muted = !audio.muted

                //audio.load()
                //$("#audio").attr("muted","")

            }, 2000);
            setTimeout(function () {
                setMarkerInfo(panoinfo);

            }, 3000);


            // setMarkerInfo(panoinfo);
            panoView.setAutoplayLoopTime(160000);
            panoView.stopEffect();
            panoView.touchable = true;
            // panoView.setOnClick(function () {
            //     panoOnClick()
            // });


        };
        panoView.playAnimation(anim);
    }

    // var btn = View.parse({
    //     id:"btn",
    //     type: "TextView",
    //     width: "200dp",
    //     contentGravity: "center",
    //     height: "40dp",
    //     fontColor: "#ffffff",
    //     text:"探秘故宫",
    //     background: "#000000",
    //     gravity : "bottom|center"
    // });

    $(document).on("click", "#btn", function () {
        startIn();
    });
    $(document).on("touchend", "#btn", function () {
        startIn();
    });

    function startIn() {

        //隐藏自身
        $(".gugong-text").hide();

        runEnter();
        //page.removeView(btn);

    }


    return panoView;
});


//------------------------------------------------------------------------------------


// let marker = [];
// let panoView = null;
// let pano = new com.vizengine.App(document.getElementById('container'), function () {
//     panoView = new com.vizengine.view.PanoView()
//     setPanoInfo(panoinfos[0]);
//
//     panoView.setOnClick(function () {
//         panoOnClick()
//     });
//     return panoView
// });

let delayShow = 0;

function setPanoInfo(panoinfoOut) {
    removeAllMarker();
    // 使用Object.assign 主要用来合并多个js对象，将源对象赋值到目标中
    // 这样做的好处是，避免函数内部的操作改变了参数（污染参数）
    let panoinfo = {}
    Object.assign(panoinfo, panoinfoOut)
    if (env() == 'test') {
        panoinfo.panoId = '[TT]' + panoinfo.panoId
    }
    var anim = new com.vizengine.animation.PanoScaleSwitchAnimation;
    panoView.setPanoId(panoinfo.panoId, function () {
        panoView.setHeading(panoinfo.heading || 0);
        panoView.setPitch(panoinfo.pitch || 0);

        //marker点延时加载 ，在欢迎页面出来之后加载
        timer = setTimeout(function () {
            setMarkerInfo(panoinfo);
        }, delayShow)
        //setMarkerInfo(panoinfo);


        //★★★这里是回调，可以用来判断首次全景加载完成，隐藏loading,显示欢迎页
        $("#loading").hide();

        if (!isShowWelcome) {
            $(".welcomPage").show();
        } else {
            $(".welcomPage").hide();
        }
        isShowWelcome = true

    },anim);

    panoView.setAutoplayEnable(true);
    panoView.setAutoplayLoopTime(160000);
    // panoView.setFov(40);
}

function setMarkerInfo(panoinfo) {
    if (panoinfo && panoinfo.marker)
        marker = [];
    for (i = 0; i < panoinfo.marker.length; i++) {
        marker[i] = new com.vizengine.view.View();
        marker[i].setId(i);
        marker[i].panoHeading = panoinfo.marker[i].heading; // marker在全景中的正北方向的偏转角度
        marker[i].panoPitch = panoinfo.marker[i].pitch; // marker在全景中的俯仰角度
        marker[i].setAnchorX(0.5); // 设置锚点的横坐标(0-1,0表示最左，1表示最右)
        marker[i].setAnchorY(0.5); // 设置锚点的纵坐标(0-1,0表示最上，1表示最下)
        marker[i].setWidth("75dp"); // 设置marker的宽度
        marker[i].setHeight("75dp"); // 设置marker的高度
        marker[i].markerinfo = panoinfo.marker[i];
        // 设置marker点击回调处理
        marker[i].setOnClick(function (e) {


            delayShow = 0; //不延时加载
            //clearInterval(timer);//点击任意marker 取消轮播
            // setPanoInfo(panoinfos[this.markerinfo.panoId]);

            //点击任意marker 恢复语音状态
            changeSceneAudio ();

            if (this.markerinfo.type == "pano") {

                let p = getPanoInfo(this.markerinfo.properties.materialId, this.markerinfo.properties.facilityId);
                setPanoInfo(p.data);
                viewSubPageElement("pano");

                isIndex = false;//点击任何全景marker都将不在首页


                //5s 显示相册5s后隐藏
                showAlbum();

                clearTimeout(hideAlbumTime)
                hideAlbum5s();

                //如果是首页的marker点 || ★★★marker点
                //console.log(this.markerinfo);

                //console.log("外：" + this.markerinfo.properties.entityId);

                ////如果是首页的marker点
                // if (indexAppearanceMarkers[this.markerinfo.id] || facToEnt[this.markerinfo.properties.facilityId]) {
                if ( facToEnt[this.markerinfo.properties.facilityId]) {
                    //if (entityArr[this.markerinfo.properties.entityId] ){

                    let curEntityID = facToEnt[this.markerinfo.properties.facilityId];

                    //console.log(curEntityID);

                    //设置子实体信息
                    changeEntityInfo(getEntityInfo(curEntityID));

                    //相册切换
                    viewFacilityList(curEntityID);

                    console.log("curEntityID   "+curEntityID);





                }

                //如果是VR模式

                if (vr) {

                    $(".feature,.home-wrap,.home-logo").hide(150);

                    $(".feature,.inner-wrap,.header-info,.back-home").hide(150);

                    $(".header-audio,.header-g-safe").hide(150);

                    $(".video-marker , .imgMarker").parent().addClass("hideMarker");
                }

            } else if (this.markerinfo.type == "threeDModel") {

                $("#threeDContainer").show();
                $(".dimensional-mask").show();

                //加载介绍数据
                $(".dim-title").html(this.markerinfo.name);
                $(".dim-info , .dimCon-viewBox p").html(this.markerinfo.properties.content);
                //展示三维
                // var model = new com.vbr3d.Model(document.getElementById("threeDContainer"));


                $(".threeD-wrap").show();
                // var vbrId = '1621729ED8FC47BAB2743DB43F728BF8'
                // var jobId = '1001261'
                var vbrId = this.markerinfo.properties.modelInfo.modelId;
                var jobId = this.markerinfo.properties.modelInfo.path;
                var modelInfo = this.markerinfo.properties.modelInfo;

                // // 新建三维模型
                model.model3dView.onModelLoadedCallback = function() {
                    $(".loader").css("display","none");
                    model.model3dView.setBackgroundTexture("http://cimg.vizen.cn/release/pic/30576f063b99cc1a5b2c68ac51686a9b.png");
                    // 调整三维模型
                    var modelPose = null
                    if (modelInfo.pose) {
                        modelPose = JSON.parse(modelInfo.pose)
                        if(modelPose != null && modelPose.matrix && modelPose.matrix.length > 0) {
                            model.model3dView.rootObject.matrix.elements = modelPose.matrix
                        }
                        if(modelPose != null && modelPose.defaultDistanceRate) {
                            model.model3dView.setDefaultDistanceRate(modelPose.defaultDistanceRate);
                        }
                        if(modelPose != null && modelPose.lookAnchor) {
                            model.model3dView.setLookAnchor(modelPose.lookAnchor);
                        }
                        if(modelPose != null && modelPose.lookatLocation) {
                            model.model3dView.setLookatLocation(modelPose.lookatLocation);
                        }
                    }
                }
                //设置三维数据加载级别为1
                model.model3dView.setLevelCount(2);
                model.setModelIdAndJobId(vbrId, jobId);


            } else if (this.markerinfo.type == "info") {

                $("#container").toggleClass("containerBlur");
                $(".imgText-img").attr("src", this.markerinfo.properties.pic);
                $(".imgText-title").html(this.markerinfo.name);
                $(".imgText-text").html(this.markerinfo.properties.content);
                $(".imgText-mask").css("display", "block");

                //隐藏元素
                viewSubPageElement("info");
                //暂停6秒后启动
                panoView.setAutoplayEnable(false);
                setTimeout(function () {
                    panoView.setAutoplayEnable(true);
                }, 6000);

            } else if (this.markerinfo.type == "video") {
                $("#video").attr("src", this.markerinfo.properties.url);
                $(".video-wrap").fadeIn(300);
                $("#video")[0].play(); //视频播放
                if (audio.play) {
                    audio.pause();//暂停
                }

            } else if (this.markerinfo.type == "audio") {
                $("#audio").attr("src", this.markerinfo.properties.url);

                audio.play();//播放
                isMusic = true;


            }
            // this.parentView.removeView(this);
            //只要有marker 被点击 则移除轮播

        });


        // 通过innerHtml自定义marker内容
        if (panoinfo.marker[i].arrtype && panoinfo.marker[i].arrtype != "") {
            let icon = new window.com.vizengine.view.ImageView()
            icon.setWidth('44dp')
            icon.setHeight('44dp')
            icon._nativeView.div.setAttribute('class', panoinfo.markers[i].arrtype)
            icon.setGravity('centerHorizontal')
            icon.setMarginTop('5dp')
            marker[i].addView(icon)
            // marker[i]._nativeView.div.innerHTML =panoinfo.markers[i].htmlStr;
        } else if (panoinfo.marker[i].type && panoinfo.marker[i].type == "info") {
            //图文marker
            //if (indexAppearanceMarkers[panoinfo.marker[i].id]) {
            //首页图文marker
            marker[i].setHeight("50pd"); // 设置marker的高度
            marker[i].setWidth("50pd"); // 设置marker的宽度
            //marker[i]._nativeView.div.style = 'display: none; visibility:hidden;';

            marker[i]._nativeView.div.innerHTML =
                "<div id='imgMarker' class='imgMarker'>" +
                "<img src='" + panoinfo.marker[i].properties.pic + "' />" +
                "</div>";
            // } else {
            //     marker[i]._nativeView.div.innerHTML =
            //         "<div id='imgMarker'>" +
            //         "<img src='" + panoinfo.marker[i].properties.pic + "' />" +
            //         "</div>";
            // }

        } else if (panoinfo.marker[i].type && panoinfo.marker[i].type == 'pano') {

            let imgurl = "http://tiles.pano.vizen.cn/" + panoinfo.marker[i].properties.panoId + "/sphere/thumb.jpg";


            //如果是首页的marker点
            if (indexAppearanceMarkers[panoinfo.marker[i].id]) {

                //tansuoImg.push(marker[i].markerinfo.properties.facilityId);
                marker[i]._nativeView.div.innerHTML =
                    `<div id='palace-marker'>
                        <p class='palace'>${panoinfo.marker[i].name}</p>
                    </div>`;

            } else {
                //默认marker
                marker[i].setHeight("100pd"); // 设置marker的高度
                marker[i].setWidth("100pd"); // 设置marker的宽度
                marker[i]._nativeView.div.innerHTML =
                    "<div id='enter-marker'>" +
                    "<p>" + panoinfo.marker[i].name + "</p>" +
                    "<img src='./images/jinru.png' alt=''>" +
                    "</div>";

                if (panoinfo.marker[i].style == 'marker-red') {   // 上箭头 下小红屋--已解决
                    marker[i].setHeight("100pd"); // 设置marker的高度
                    marker[i].setWidth("100pd"); // 设置marker的宽度
                    marker[i]._nativeView.div.innerHTML =

                        "<div id='another-marker'>" +
                        "<p>" + panoinfo.marker[i].name + "</p>" +
                        "<img class='another-img' src='./images/qita.png' alt=''>" +
                        "</div>";
                }

                if (panoinfo.marker[i].style == 'marker-black') {  //进入--已解决

                }

                if (panoinfo.marker[i].style == 'house') {  // 屋子造型--已解决
                    marker[i].setHeight("100pd"); // 设置marker的高度
                    marker[i].setWidth("100pd"); // 设置marker的宽度
                    marker[i]._nativeView.div.innerHTML =
                        "<div id='home-marker'>" +
                        "<div class='blackHouse'></div>" +
                        "<div class='marker-name'><p>" + panoinfo.marker[i].name + "</p></div>" +
                        "</div>"
                }

                if (panoinfo.marker[i].style == 'right') {   // 右箭头
                    marker[i].setHeight("100pd");
                    marker[i].setWidth("100pd");
                    marker[i]._nativeView.div.innerHTML =
                        "<div id='right-marker'>" +
                        "<div id='marker-name'>" + panoinfo.marker[i].name + "</div>" +
                        "<div id='movingArrowRight'></div>" +
                        "</div>";
                }

                if (panoinfo.marker[i].style == 'left') {  // 左箭头 -- 已解决
                    marker[i].setHeight("100pd");
                    marker[i].setWidth("100pd");
                    marker[i]._nativeView.div.innerHTML =
                        "<div id='left-marker'>" +
                        "<div id='movingArrowLeft'></div>" +
                        "<div id='marker-name'>" + panoinfo.marker[i].name + "</div>" +
                        "</div>";
                }

                if (panoinfo.marker[i].style == 'top') {  // 上箭头 -- 已解决
                    marker[i].setHeight("100pd");
                    marker[i].setWidth("100pd");
                    marker[i]._nativeView.div.innerHTML =
                        // "<div id='top-marker'>" +
                        // "<div class='movingArrowDown'></div>" +
                        // "<div class='marker-name'><p>" + panoinfo.marker[i].name + "</p></div>" +
                        // "</div>";
                        "<div id='another-marker'>" +
                        "<img class='row' src='./images/row.png' alt=''>" +
                        "<p>" + panoinfo.marker[i].name + "</p>" +
                        "<img class='another-img' src='./images/another.png' alt=''>" +
                        "</div>"
                }

                if (panoinfo.marker[i].style == 'normal') {  // 圆点--已解决
                    marker[i].setHeight("100pd");
                    marker[i].setWidth("100pd");
                    marker[i]._nativeView.div.innerHTML =
                        // "<div id='round-marker'>" +
                        // "<div id='big-round'></div>" +
                        // "<div id='marker-name'><p>" + panoinfo.marker[i].name + "</p></div>" +
                        // "</div>";

                        "<div id='enter-marker'>" +
                        "<p>" + panoinfo.marker[i].name + "</p>" +
                        "<img src='./images/enter.png' alt=''>" +
                        "</div>"
                }

            }
        }
        else if (panoinfo.marker[i].type == 'threeDModel') {// 三维marker
            marker[i].setHeight("150pd"); // 设置marker的高度
            marker[i].setWidth("150pd"); // 设置marker的宽度
            marker[i]._nativeView.div.innerHTML =
                `<div class='threedMarker threeDimensional-marker tongshi'> 
                    <img src='${panoinfo.marker[i].linkUrl}'/>
                </div>`
        }
        else if (panoinfo.marker[i].type && panoinfo.marker[i].type == 'info') {//图文
            marker[i]._nativeView.div.innerHTML =
                `<div id='imgMarker'>
                    <img src='${panoinfo.marker[i].properties.pic}' />
                </div>`;
        }
        else if (panoinfo.marker[i].type && panoinfo.marker[i].type == 'video') { //视频marker
            marker[i]._nativeView.div.innerHTML =
                `<div id='video-marker'>
                    <img class='video-m-img' src='http://view.luna.visualbusiness.cn/release/pic/poi/7d5803a9279310223f94ed10f9a3981d.jpg'/>
                    <img class='video-m-btn' src='./images/playBtn.png' />
               </div>`;
        }
        else if (panoinfo.marker[i].type && panoinfo.marker[i].type == 'audio') {
            let textMarker = new window.com.vizengine.view.TextView();
            textMarker.setFontColor('#FFFFFF');
            textMarker.setFontSize('13dp');
            textMarker.setText(panoinfo.marker[i].name);
            textMarker.setPadding('5dp', '4dp', '5dp', '4dp');
            textMarker.setGravity('centerHorizontal');
            marker[i].addView(textMarker)
        }
        else {
            let textMarker = new window.com.vizengine.view.TextView();
            textMarker.setFontColor('#FFFFFF');
            textMarker.setFontSize('13dp');
            textMarker.setText(panoinfo.marker[i].name);
            textMarker.setPadding('5dp', '4dp', '5dp', '4dp');
            textMarker.setGravity('centerHorizontal');
            marker[i].addView(textMarker)
        }
        panoView.addView(marker[i]);
    }
}

function removeAllMarker() {//移除所有marker
    panoView.clearViews();
}

function randomInt(num) {
    return Math.floor(num * Math.random());
}

function randomColor() { //随机颜色值
    return "(" + randomInt(255) + "," + randomInt(255) + "," + randomInt(255) + ")";
}

//定义连个全景，进行切换演示 clearInterval()
// let panoArr = ["E699DB178FD54C1CA4DC7C30549AEDE5", "0CD773F0C6964DD9B08EC4F594323F1E","3A000AD7C2DA404497B4753E99DA5FB2"];
//let timer = setInterval(show, 30000);//每隔2秒改变一次
//let currentIndex = 0;

//function show() {};

//setPanoInfo(panoinfos[0]);

//全景点击后停止转动（同时隐藏当前的所有元素）
let autoplay = true;

function panoOnClick() {
    //panoView.setAutoplayEnable(autoplay);


    autoplay = !autoplay;
    panoView.setAutoplayEnable(autoplay);

    //显示，隐藏maker
    panoView.clearViews();

    if (autoplay) {
        for (i = 0; i < marker.length; i++) {
            //console.log(marker[i]);
            panoView.addView(marker[i]);
        }
    }

    //单击隐藏其他元素
    if (isIndex) {
        if (vr) {
            panoView.clearViews();
            //只显示全景marker
            for (i = 0; i < marker.length; i++) {
                //console.log(marker[i]);
                if (marker[i].markerinfo.type && marker[i].markerinfo.type == "pano") {
                    panoView.addView(marker[i]);
                }
            }
        } else {
            $(".header,.feature,.home-wrap").fadeToggle(150);
        }
    } else {
        if (vr) {
            panoView.clearViews();
            //只显示全景marker
            if (marker[i].markerinfo.type && marker[i].markerinfo.type == "pano") {
                if (marker[i].type && marker[i].type == "pano") {
                    panoView.addView(marker[i]);
                }
            }
        } else {
            $(".header,.feature,.inner-wrap,.header-info").fadeToggle(150);
        }
    }

    //暂停6秒后启动
    panoView.setAutoplayEnable(false);
    setTimeout(function () {
        panoView.setAutoplayEnable(true);
    }, 6000);

}


function setCookie(name, value) {
    let Days = 30;
    let exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}

function getCookie(name) {
    let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}


//vr
let vr = false;
$(".header-vr").click(function () {
    // $("#rightEye").trigger("click");
    if (isIndex) {
        $(".feature,.home-wrap,.home-logo,.header-map").fadeToggle(150);
    } else {
        $(".feature,.inner-wrap,.header-info,.back-home").fadeToggle(150);
    }
    $(".header-audio,.header-g-safe").fadeToggle(150);


    if (!vr) {
        panoView.setVREnable(true);
        vr = true;

        //$("#video-marker , #imgMarker").parent("div").hide().css({"width":"0px !important"});
        //$(".video-marker , .imgMarker , .threedMarker").parent().addClass("hideMarker");

        //隐藏maker
        panoView.clearViews();

        //显示maker
        //只显示全景marker
        for (i = 0; i < marker.length; i++) {
            //console.log(marker[i]);
            if (marker[i].markerinfo.type && marker[i].markerinfo.type == "pano") {
                panoView.addView(marker[i]);
            }
        }

    } else {
        panoView.setVREnable(false);
        vr = false;

        // $(".video-marker , .imgMarker").parent().removeClass("hideMarker");
        //显示maker
        for (i = 0; i < marker.length; i++) {
            panoView.addView(marker[i]);
        }
    }
});

//重力感应
$(".header-g-safe").click(function () {
    if ($(".g-safe-img1").css("visibility") == "visible" && $(".g-safe-img2").css("visibility") == "hidden") {
        panoView.setGravityEnable(true)
        // console.log("重力感应开启了");
    } else if ($(".g-safe-img2").css("visibility") == "visible" && $(".g-safe-img1").css("visibility") == "hidden") {
        panoView.setGravityEnable(false)
        // console.log("重力感应关闭了");
    }
});


window.onload = function () {
    //分享
    let shareUrl = null;
    let shareTitle = appInfo.data.shareTitle;
    let shareDesc = appInfo.data.shareDesc;
    let shareImg = appInfo.data.thumbnail;
    //getShareInfoSub(shareUrl, shareTitle, shareDesc, shareImg);
};

//语音介绍
var vioce = $("#audioIntro")[0];

//微信
audio.play();
let ua = window.navigator.userAgent.toLowerCase();
document.addEventListener('DOMContentLoaded', function () {
    function audioAutoPlay() {
        //let audio = $("#audio")[0];
        if (audio) {
            // $("#audio")[0].volume = 0;
            audio.play();
            console.log("1");
            //audio.pause()
            if (ua.match(/MicroMessenger/ig) == 'micromessenger') {
                document.addEventListener("WeixinJSBridgeReady", function () {
                    $("#audio")[0].volume = 0;
                    audio.play();
                    // console.log("2");
                    // audio.pause()
                }, false);
            }
            $(".audio-img1").addClass("audio-img1-rotate");
        }
    }

    audioAutoPlay();
});

//ios 非微信下 bug 必须要touch
let state = 0;
document.addEventListener('touchstart', function () {
    if (state == 0) {
        audio.play();
        state = 1;
    }
}, false);

let isVioce = false;
//音乐播放
$(".header-audio").click(function () {

    // //判断语音介绍是否播放
    if (isVioce) { //如果在播放
        vioce.pause();
        isVioce = false;
        $(".voice").removeClass("active");
    }

    if (audio !== null) {
        if (audio.paused) {
            audio.play();
            isMusic = true;
        } else {
            audio.pause();
            isMusic = false;
        }
    }
});


$(".voice").click(function () {
    //背景音乐停止
    //console.log(audio.play);

    //判断自身是否播放
    if (!isVioce) { //未播放
        vioce.play();
        isVioce = true;
        if (isMusic) {
            audio.pause();
            $(".audio-img1").removeClass("audio-img1-rotate");
        }
    }else { // 播放
        vioce.pause();
        isVioce = false;

        if (isMusic) {
            audio.play();
            $(".audio-img1").addClass("audio-img1-rotate");
        }
    }

});

vioce.addEventListener('ended', function () {
    console.log("音频播放完成");
    $(".voice").removeClass("active");
    isVioce = false;
    if (isMusic) {
        audio.play();
        $(".audio-img1").addClass("audio-img1-rotate");
    }
}, false);


//场景改版，恢复语音状态
function changeSceneAudio () {

    //切换任何场景 voice 恢复初始状态
    vioce.pause();
    isVioce = false;
    $(".voice").removeClass("active");


    //判断背景音乐是否播放
    if(isMusic){
        audio.play();
        $(".audio-img1").addClass("audio-img1-rotate");
    }



}


//map data
var mapObj;
$.ajax({
    url: 'js/map_data_20180930.txt',
    dataType: 'text',
    success: function (data) {
        mapObj = JSON.parse(data);
        // console.log(JSON.parse(data));
    }
});

var mapLabel = "";
for (let i = 0; i < mapObj.length; i++) {

    if (mapObj[i].group_name == "卫生间") {//卫生间 weishengjian
        for (let j = 0; j < mapObj[i].data.length; j++) {
            mapLabel += `
                <div class="architecture-marker" id="${mapObj[i].data[j].id}" group="${mapObj[i].group_name}" left="${mapObj[i].data[j].point_x}" top="${mapObj[i].data[j].point_y}" style="left:${mapObj[i].data[j].point_x}%; top:${mapObj[i].data[j].point_y}%;">
                    <img class="architecture-icon" src="./images/weishengjian.png">
                    <div class="imgMarker-name noRecommend">
                        <div class="core">${mapObj[i].data[j].name}<p class="v-arrow">〉</p></div>
                    </div>
                </div>
                `
        }
    }
    if (mapObj[i].group_name == "其他") {//其他 qitaIcon
        for (let j = 0; j < mapObj[i].data.length; j++) {
            mapLabel += `
                <div class="architecture-marker" id="${mapObj[i].data[j].id}" group="${mapObj[i].group_name}" left="${mapObj[i].data[j].point_x}" top="${mapObj[i].data[j].point_y}" style="left:${mapObj[i].data[j].point_x}%; top:${mapObj[i].data[j].point_y}%;">
                    <img class="architecture-icon" src="./images/qitaIcon.png">
                    <div class="imgMarker-name noRecommend">
                        <div class="core">${mapObj[i].data[j].name}<p class="v-arrow">〉</p></div>
                    </div>
                </div>
                `
        }
    }

    if (mapObj[i].group_name == "商店") {//商店 shangpian

        for (let j = 0; j < mapObj[i].data.length; j++) {
            mapLabel += `
                <div class="architecture-marker" id="${mapObj[i].data[j].id}" group="${mapObj[i].group_name}" left="${mapObj[i].data[j].point_x}" top="${mapObj[i].data[j].point_y}" style="left:${mapObj[i].data[j].point_x}%; top:${mapObj[i].data[j].point_y}%;">
                    <img class="architecture-icon" src="./images/shangpian.png">
                    <div class="imgMarker-name noRecommend">
                        <div class="core">${mapObj[i].data[j].name}<p class="v-arrow">〉</p></div>
                    </div>
                </div>
                `
        }

    }
    if (mapObj[i].group_name == "餐饮") {//餐饮 canyin

        for (let j = 0; j < mapObj[i].data.length; j++) {
            mapLabel += `
                <div class="architecture-marker" id="${mapObj[i].data[j].id}" group="${mapObj[i].group_name}" left="${mapObj[i].data[j].point_x}" top="${mapObj[i].data[j].point_y}" style="left:${mapObj[i].data[j].point_x}%; top:${mapObj[i].data[j].point_y}%;">
                    <img class="architecture-icon" src="./images/canyin.png">
                    <div class="imgMarker-name noRecommend">
                        <div class="core">${mapObj[i].data[j].name}<p class="v-arrow">〉</p></div>
                    </div>
                </div>
                `
        }

    }
    if (mapObj[i].group_name == "宫殿") {//宫殿 jianzhu
        for (let j = 0; j < mapObj[i].data.length; j++) {
            if (mapObj[i].data[j].recommend == "0") {
                mapLabel += `
                    <div class="architecture-marker show" id="${mapObj[i].data[j].id}" type="pano" group="${mapObj[i].group_name}" left="${mapObj[i].data[j].point_x}" top="${mapObj[i].data[j].point_y}" style="left:${mapObj[i].data[j].point_x}%; top:${mapObj[i].data[j].point_y}%;">
                        <img class="architecture-icon" src="./images/jianzhu.png">
                        <div class="imgMarker-name noRecommend">
                            <div class="core">${mapObj[i].data[j].name}<p class="v-arrow"><img src="./images/mapArrow.png" alt=""></p></div>
                        </div>
                    </div>
                    `
            } else {
                mapLabel += `
                    <div class="architecture-marker show" id="${mapObj[i].data[j].id}" type="pano" group="${mapObj[i].group_name}" left="${mapObj[i].data[j].point_x}" top="${mapObj[i].data[j].point_y}" style="left:${mapObj[i].data[j].point_x}%; top:${mapObj[i].data[j].point_y}%;">
                        <img class="architecture-icon" src="./images/jianzhu.png">
                        <div class="imgMarker-name active">
                            <div class="core">${mapObj[i].data[j].name}<p class="v-arrow"><img src="./images/mapArrow.png" alt=""></p></div>
                        </div>
                    </div>
                    `
            }
        }
    }
}

var clockShow = `
    <div class="map-zbz" style="left:75%; top:15%;">
        <img src="./images/zhongbiaozhan.png"/>
    </div>`;


$("#bigImgMarker").html(mapLabel + clockShow);


//地图操作

//美化滚动条
$(".map-wrap").niceScroll();


function initTouchEvents() {
    if (self.isPC()) {//PC
        console.log("pc");
        $(".map-wrap")[0].addEventListener('mousedown', touch, false);
        $(".map-wrap")[0].addEventListener('mousemove', touch, false);
        $(".map-wrap")[0].addEventListener('mouseup', touch, false);

        let isClick = false;

        //记录鼠标起始坐标
        let startX, startY;

        //记录地图当前位置
        let mapX, mapY;

        function touch(event) {
            var event = event || window.event;

            switch (event.type) {
                case "mousedown": {
                    isClick = true;

                    startX = event.clientX;
                    startY = event.clientY;

                    mapX = $(".map-wrap").scrollLeft();
                    mapY = $(".map-wrap").scrollTop();
                    //console.log(isClick);
                    //$("#start").html(`PC-起始位置：${event.clientX} ,${event.clientY}`);
                    break;
                }
                case "mouseup": {
                    isClick = false;
                    //$("#end").html(`PC-结束位置：${event.clientX} ,${event.clientY}`);
                    break;
                }
                case "mousemove": {
                    event.preventDefault();
                    //console.log(isClick);
                    if (isClick) {
                        //$("#moving").html(`PC-拖动位置: ${event.clientX}, ${event.clientY}`);
                        //$("#moveVal").html(`PC-拖动差值: ${event.clientX - startX} ,${event.clientY - startY}`);

                        //改变地图位置
                        $(".map-wrap").scrollLeft(mapX - (event.clientX - startX));
                        $(".map-wrap").scrollTop(mapY - (event.clientY - startY));


                    } else {
                        //console.log("我当前是鼠标移动");
                    }
                    break;
                }
            }
        }
    } else {//移动设备
        //console.log("wap");
        $(".map-wrap")[0].addEventListener('touchstart', touch, false);
        $(".map-wrap")[0].addEventListener('touchmove', touch, false);
        $(".map-wrap")[0].addEventListener('touchend', touch, false);

        //记录鼠标起始坐标
        let startX, startY;

        //记录地图当前位置
        let mapX, mapY;

        function touch(event) {
            var event = event || window.event;

            switch (event.type) {
                case "touchstart": {
                    startX = event.touches[0].clientX;
                    startY = event.touches[0].clientY;

                    mapX = $(".map-wrap").scrollLeft();
                    mapY = $(".map-wrap").scrollTop();

                    //console.log(`WAP-起始位置：${event.touches[0].clientX} ,${event.touches[0].clientY}`);
                    break;
                }
                case "touchend": {
                    //console.log(`WAP-结束位置：${event.changedTouches[0].clientX} ,${event.changedTouches[0].clientY}`);
                    break;
                }
                case "touchmove": {
                    event.preventDefault();
                    // console.log(`WAP-拖动位置: ${event.touches[0].clientX}, ${event.touches[0].clientY}`);
                    // console.log(`WAP-拖动差值: ${event.touches[0].clientX - startX} ,${event.touches[0].clientY - startY}`);

                    //改变地图位置
                    $(".map-wrap").scrollLeft(mapX - (event.touches[0].clientX - startX));
                    $(".map-wrap").scrollTop(mapY - (event.touches[0].clientY - startY));
                    break;
                }
            }
        }
    }
}

function isPC() {  //判断pc端与移动端

    var userAgentInfo = navigator.userAgent;
    var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");  //判断用户代理头信息
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) != -1) {
            flag = false;
            break;
        }
    }
    return flag;   //true为pc端，false为非pc端

}

initTouchEvents();

//地图marker点击


$(document).on("click touchend", ".imgMarker-name", function () {

    console.log("imgMarker-name");

    //为景点marker才能跳转全景
    if ($(this).parents(".architecture-marker").attr("type")) {

        isIndex = false;

        showAlbum();
        clearTimeout(hideAlbumTime);
        hideAlbum5s();



        //当前浏览的全景加上标识 移除上一个场景的浏览状态
        $(".architecture-marker[group='宫殿'] .architecture-icon").removeClass("curView");
        $(".architecture-marker[group='宫殿'] .architecture-icon").attr("src","./images/jianzhu.png");
        $(this).siblings(".architecture-icon").addClass("active curView");
        $(this).siblings(".architecture-icon").attr({"src":"./images/icon-guankan.png"});




        //隐藏地图
        $(".map-mask").hide();

        //恢复初始状态
        $(".map-box").removeClass("active");
        $("#bigImgMarker").hide().addClass("hideName");
        $("#baDaDian").show();
        $(".select-btn-item").removeClass("active");
        $(".architecture-marker").removeClass("show");
        $(".architecture-marker[group='宫殿']").toggleClass("show");
        $("#map-big").removeClass("active");


        //标记为已查看
        //$(this).siblings(".architecture-icon").addClass("active");

        //获取并展示设施信息
        let curEntityID = $(this).parents(".architecture-marker").attr("id");
        //console.log(entityId);

        let pInfo = getPanoInfoBySubEntityId(curEntityID);
        //console.log(pInfo);
        setPanoInfo(pInfo);

        viewSubPageElement("pano");
        changeEntityInfo(getEntityInfo(curEntityID));


        //相册切换
        viewFacilityList(curEntityID);



    }

});


//微信相关---------------------------------------------------------------------------
//注意 ： 分享和导航在微信内的服务，必须使用正式的vizen.cn的域名才可以，share.js里涉及到微信签名和授权，所以本地地址和其他域名是不能正常调用的

//getShareInfoSub()函数是share.js的分享函数
// 参数包含 url, title, desc, imgUrl, success, cancel, callback
// 分享的url ，标题，描述，分享图片地址，成功回调，取消回调，返回函数
//getShareInfoSub(window.location.href, "分享标题", "分享描述分享描述分享描述分享描述", "http://cemp.vizen.cn/images/product-list/logo.png", null, null, null);
//getShareInfoSub(window.location.href, appInfo.data.name, appInfo.data.description, "appInfo.data.logo", null, null, null);

//判断是否是微信里
function is_weixn() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
    } else {
        return false;
    }
}

//地址相关信息  //lnglat: Array [ 116.39704, 39.91539 ]
var navDestination = {
    "lat": baseEntity.data.lnglat[1], //纬度，腾讯或者高德坐标
    "lng": baseEntity.data.lnglat[0],  //经度，腾讯或者高德坐标
    "title": baseEntity.data.name,
    "address": baseEntity.data.address
};
$(document).ready(function () {
	//分享到微博
	var call_back_url = "https://servergugong.vizen.cn/gugong/call_back_code.jsp";
	var client_id = "3910017298";
	var oauthurl = "https://api.weibo.com/oauth2/authorize?client_id="+client_id+"&response_type=code&redirect_uri="+call_back_url;
	$(".affirm").on("click",function(){
		window.location.href=oauthurl;
	});
	//微信分享

    if(appInfo.data.thumbnail.indexOf("http") == -1){
        appInfo.data.thumbnail = "http:" + appInfo.data.thumbnail
    }
	getShareInfoSub(window.location.href, appInfo.data.shareTitle, appInfo.data.shareDesc, appInfo.data.thumbnail, null, null, null);
	  //导航按钮点击事件
    function tomap()
    {
        // alert($(this).attr("lat"));
        if ($(this).attr("lat") && $(this).attr("lat") != "") {
            navDestination.lat = $(this).attr("lat");
            navDestination.lng = $(this).attr("lng");
            navDestination.title = $(this).attr("title");
            navDestination.address = $(this).attr("address");
        }
        if (!is_weixn()) {
            //不是微信，直接跳转导航地址
            //腾讯导航地址
            // window.location.href="//apis.map.qq.com/uri/v1/routeplan?type=drive&to=" + navDestination.title + "&tocoord="+ navDestination.lat +"," + navDestination.lng + "&policy=1&referer=myapp";
            //高德导航地址
            window.location.href = "//uri.amap.com/navigation?from=&to=" + navDestination.lng + "," + navDestination.lat + "," + navDestination.title + "&via=&mode=car&policy=0&src=mypage&coordinate=gaode&callnative=0";

            //此处也可以使用其他跳转地址 例如其他uriapi等

        } else {
            //是微信，调用微信位置服务，调用此接口的前提是必须在微信里，并且进行了微信初始化  详见share.js里的wx.config 和wx.ready
            wx.openLocation({
                latitude: Number(navDestination.lat),
                longitude: Number(navDestination.lng),
                name: navDestination.title,
                address: navDestination.address,
                scale: 14,
                infoUrl: 'http://webapp.vizen.cn/'
            });
        }
    }
    $(document).on("click", "#mapNav", function () {
        tomap();
    });
    $(document).on("touchend", "#mapNav", function () {
        tomap();
    });
});

//设置地图背景
var mapImg = "./images/map1.jpg";
$('#bacMap').attr('src', mapImg).on('load', function() {
    console.log(mapImg);
    //$(this).remove(); // prevent memory leaks as @benweet suggested
    $("#mapBox").css('background-image', `url(${mapImg})`);
    // $("#baDaDian").css("opacity","1");
});
//美化购票页面滚动条
$("#buyTicket").click(function () {
   $("#buyBox").attr("src","http://gugong.228.com.cn").show();
   $("#buyClose").show();
});
$("#buyClose").click(function () {
    $(this).hide();
    $("#buyBox").hide();
});

$("iframe html").niceScroll();